<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="区域名称">
                            <el-input v-model="searchForm.areaName" placeholder="请输入区域名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报警状态">
                            <el-select v-model="searchForm.alarmStatus" placeholder="请选择报警状态" clearable
                                style="width: 100%">
                                <el-option label="开启" :value="1" />
                                <el-option label="关闭" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报警等级">
                            <el-select v-model="searchForm.alarmLevel" placeholder="请选择报警等级" clearable
                                style="width: 100%">
                                <el-option v-for="item in alarmLevelOptions" :key="item.dictValue"
                                    :label="item.dictLabel" :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" @click="handleSearch">查询</el-button>
                            <el-button @click="handleReset">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <!-- 数据表格 -->
        <el-card class="table-card mt-2">
             <el-button type="primary" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>新增配置
                </el-button>
                <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
                    <el-icon>
                        <Delete />
                    </el-icon>批量删除
                </el-button>
            <div class="table-container mt-2">
                <el-table ref="tableRef" :data="tableData" border v-loading="loading"
                    @selection-change="handleSelectionChange" style="width: 100%">
                    <el-table-column type="selection" width="55" align="center" fixed="left" />
                    <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
                    <el-table-column prop="areaName" label="区域名称" align="center"/>
                    <el-table-column label="报警状态" align="center">
                        <template #default="{ row }">
                                <el-tag v-if="row.alarmStatus === 1" type="success">开启</el-tag>  
                                <el-tag v-else type="danger">关闭</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="报警规则" align="center">
                        <template #default="{ row }">
                            <el-popover placement="top-start" title="报警规则详情" trigger="hover">
                                <template #reference>
                                    <el-button type="primary" link>查看规则</el-button>
                                </template>
                                <div v-if="row.rules && row.rules.length > 0">
                                    <div v-for="(rule, index) in row.rules" :key="index" class="rule-item">
                                        <div>{{rule}}</div>
                                    </div>
                                </div>
                                <div v-else>暂无规则</div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column prop="pushFrequency" label="推送频率(分钟)" align="center"/>
                    <el-table-column label="报警等级" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getAlarmLevelTagType(row.alarmLevel)">
                                {{ row.alarmLevel }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="推送方式" align="center">
                        <template #default="{ row }">
                            <el-tag  class="method-tag">
                                {{ row.pushMethod }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recipientId" label="接收人" align="center" >
                        <template #default="{ row }">
                            <el-tag>
                                {{ getName(pushObjectOptions,row.recipientId ,'id','name') }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
                            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="1000px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="区域名称" prop="areaAlarmId">
                            <el-select v-model="formData.areaAlarmId" placeholder="请选择区域" filterable style="width: 100%">
                                <el-option v-for="item in regionOptions" :key="+item.id" :label="item.name"
                                    :value="+item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="报警状态" prop="alarmStatus">
                            <el-radio-group v-model="formData.alarmStatus">
                                <el-radio :label="1">开启</el-radio>
                                <el-radio :label="0">关闭</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="报警等级" prop="alarmLevel">
                            <el-select v-model="formData.alarmLevel" placeholder="请选择报警等级" style="width: 100%">
                                <el-option v-for="item in alarmLevelOptions" :key="+item.dictValue"
                                    :label="item.dictLabel" :value="+item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="推送频率" prop="pushFrequency">
                            <el-input-number v-model="formData.pushFrequency" :min="1" :max="1440"
                                controls-position="right" style="width: 100%" placeholder="请输入推送频率(分钟)" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="推送方式" prop="pushMethod">
                            <el-select v-model="formData.pushMethod" placeholder="请选择推送方式" style="width: 100%">
                                <el-option v-for="item in pushMethodOptions" :key="item.id+''" :label="item.name"
                                    :value="item.id+''" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="推送对象" prop="recipientId">
                            <el-select v-model="formData.recipientId" placeholder="请选择推送对象" style="width: 100%">
                                <el-option v-for="item in pushObjectOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 报警规则配置 -->
                <el-form-item label="报警规则">
                    <div class="rules-container">
                        <div v-for="(rule, index) in formData.rules" :key="index" class="rule-item">
                            <el-row :gutter="20">
                                <el-col :span="5">
                                    <el-select v-model="rule.parameterId" placeholder="监测量" style="width: 100%">
                                        <el-option v-for="item in monitoringTypeOptions" :key="item.id"
                                            :label="item.name" :value="item.id" />
                                    </el-select>
                                </el-col>
                                <el-col :span="5">
                                    <el-select v-model="rule.comparisonOperator" placeholder="条件" style="width: 100%">
                                        <el-option label=">" value=">" />
                                        <el-option label="<" value="<" />
                                        <el-option label="=" value="=" />
                                        <el-option label=">=" value=">=" />
                                        <el-option label="<=" value="<=" />
                                    </el-select>
                                </el-col>
                                <el-col :span="4">
                                    <el-input-number v-model="rule.thresholdValue" placeholder="阈值" :precision="2"
                                        style="width: 100%" />
                                </el-col>
                                <el-col :span="4">
                                    <el-input-number v-model="rule.duration" placeholder="持续时间" :min="1"
                                        style="width: 100%" />
                                </el-col>
                                <el-col :span="4">
                                    <span>分钟</span>
                                </el-col>
                                <el-col :span="2">
                                    <el-button type="danger" link @click="removeRule(index)"
                                        :disabled="formData.rules.length <= 1">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </el-button>
                                </el-col>
                            </el-row>
                        </div>
                        <el-button type="primary" link @click="addRule">
                            <el-icon>
                                <Plus />
                            </el-icon>添加规则
                        </el-button>
                    </div>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Refresh } from '@element-plus/icons-vue'

// API接口
import {
    getRegionList,
    getMonitoringTypeList,
    getConditionList,
    getPushObjectList,
    getAlarmLevelList,
    getPushMethodList,
    getRegionalAlarmConfigList,
    getRegionalAlarmConfigDetail,
    addRegionalAlarmConfig,
    updateRegionalAlarmConfig,
    deleteRegionalAlarmConfig,
    deleteAlarmRule
} from '@/api/dispatch/affair/callSetting'

// 响应式数据
const loading = ref(false)
const tableRef = ref()
const formRef = ref()

// 数据存储
const tableData = ref([])
const selectedRows = ref([])

// 下拉选项数据
const regionOptions = ref([])
const monitoringTypeOptions = ref([])
const conditionOptions = ref([])
const pushObjectOptions = ref([])
const alarmLevelOptions = ref([])
const pushMethodOptions = ref([])

// 搜索表单
const searchForm = reactive({
    areaName: '',
    alarmStatus: null,
    alarmLevel: ''
})

// 分页参数
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 对话框控制
const dialog = reactive({
    visible: false,
    title: '新增区域报警配置'
})

// 表单数据
const formData = reactive({
    regionalAlarmConfigId: null,
    areaName: '',
    alarmStatus: 1,
    alarmLevel: '',
    pushFrequency: 30,
    pushMethod: '',
    recipientId: null,
    rules: [
        {
            ruleId: null,
            parameterId: null,
            comparisonOperator: '>',
            thresholdValue: null,
            duration: 5
        }
    ],
    remark: ''
})

// 表单验证规则
const formRules = reactive({
    areaName: [
        { required: true, message: '请选择区域名称', trigger: 'change' }
    ],
    alarmStatus: [
        { required: true, message: '请选择报警状态', trigger: 'change' }
    ],
    alarmLevel: [
        { required: true, message: '请选择报警等级', trigger: 'change' }
    ],
    pushFrequency: [
        { required: true, message: '请输入推送频率', trigger: 'blur' }
    ],
    pushMethod: [
        { required: true, message: '请选择推送方式', trigger: 'change' }
    ],
    recipientId: [
        { required: true, message: '请选择推送对象', trigger: 'change' }
    ]
})

// 计算属性
const getAlarmLevelTagType = (level) => {
    const types = {
        '普通': 'info',
        '重要': 'warning',
        '危急': 'danger'
    }
    return types[level] || 'info'
}

const getAlarmLevelLabel = (level) => {
    const item = alarmLevelOptions.value.find(item => item.dictValue === level)
    return item ? item.dictLabel : level
}

const getPushMethods = (pushMethod) => {
    const methods = {
        '1': '短信',
        '2': '邮件',
        '3': '系统通知'
    }
    return pushMethod ? [methods[pushMethod]] : []
}

// 初始化加载数据
onMounted(() => {
    loadAllData()
})

// 加载所有数据
const loadAllData = async () => {
    try {
        await Promise.all([
            loadDropdownOptions(),
            loadTableData()
        ])
    } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
    }
}

// 加载下拉选项数据
const loadDropdownOptions = async () => {
    try {
        const [
            regionRes,
            monitoringTypeRes,
            conditionRes,
            pushObjectRes,
            alarmLevelRes,
            pushMethodRes
        ] = await Promise.all([ 
            getRegionList(),
            getMonitoringTypeList(),
            getConditionList(),
            getPushObjectList(),
            getAlarmLevelList(),
            getPushMethodList()
        ])

        regionOptions.value = regionRes.data || []
        console.log(regionOptions.value);
        
        monitoringTypeOptions.value = monitoringTypeRes.data || []
        conditionOptions.value = conditionRes.data || []
        pushObjectOptions.value = pushObjectRes.data || []
        alarmLevelOptions.value = alarmLevelRes.data || []
        pushMethodOptions.value = pushMethodRes.data || []
    } catch (error) {
        console.error('加载下拉选项失败:', error)
        throw error
    }
}

// 加载表格数据
const loadTableData = async () => {
    try {
        loading.value = true
        const params = {
            pageNum: pagination.currentPage,
            pageSize: pagination.pageSize,
            ...searchForm
        }

        const res = await getRegionalAlarmConfigList(params)
        tableData.value = res.rows || []
        pagination.total = res.total || 0
    } catch (error) {
        console.error('加载表格数据失败:', error)
        throw error
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    pagination.currentPage = 1
    loadTableData()
}

// 重置搜索
const handleReset = () => {
    Object.assign(searchForm, {
        areaName: '',
        alarmStatus: null,
        alarmLevel: ''
    })
    handleSearch()
}

// 刷新数据
const refreshData = () => {
    loadAllData()
    ElMessage.success('数据刷新成功')
}

// 选择行
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    loadTableData()
}

// 当前页变化
const handleCurrentChange = (page) => {
    pagination.currentPage = page
    loadTableData()
}

// 新增
const handleAdd = () => {
    dialog.title = '新增区域报警配置'
    dialog.visible = true
    resetForm()
}

// 编辑
const handleEdit = async (row) => {
    try {
        loading.value = true
        const res = await getRegionalAlarmConfigDetail(row.regionalAlarmConfigId)
        dialog.title = '编辑区域报警配置'
        dialog.visible = true
        Object.assign(formData, res.data)
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    } finally {
        loading.value = false
    }
}

// 删除
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(`确定删除区域报警配置 "${row.areaName}" 吗？`, '提示', {
            type: 'warning'
        })

        await deleteRegionalAlarmConfig([row.regionalAlarmConfigId])
        ElMessage.success('删除成功')
        await loadTableData()
    } catch {
        // 用户取消删除
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
    }

    try {
        await ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
            type: 'warning'
        })

        const ids = selectedRows.value.map(item => item.regionalAlarmConfigId)
        await deleteRegionalAlarmConfig(ids)
        ElMessage.success('删除成功')
        selectedRows.value = []
        await loadTableData()
    } catch {
        // 用户取消删除
    }
}

// 状态切换
const handleStatusChange = async (row) => {
    try {
        const newStatus = row.alarmStatus
        await updateRegionalAlarmConfig({
            ...row,
            alarmStatus: newStatus
        })
        ElMessage.success('状态更新成功')
    } catch (error) {
        console.error('状态更新失败:', error)
        ElMessage.error('状态更新失败')
        // 回滚状态
        row.alarmStatus = row.alarmStatus === 1 ? 0 : 1
    }
}

// 添加规则
const addRule = () => {
    formData.rules.push({
        ruleId: null,
        parameterId: null,
        comparisonOperator: '>',
        thresholdValue: null,
        duration: 5
    })
}

// 删除规则
const removeRule = async (index) => {
    const rule = formData.rules[index]
    if (rule.ruleId) {
        try {
            await ElMessageBox.confirm('确定删除这条报警规则吗？', '提示', {
                type: 'warning'
            })
            await deleteAlarmRule(rule.ruleId)
        } catch {
            return // 用户取消删除
        }
    }
    formData.rules.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
    try {
        await formRef.value.validate()

        if (formData.regionalAlarmConfigId) {
            await updateRegionalAlarmConfig(formData)
            ElMessage.success('修改成功')
        } else {
            await addRegionalAlarmConfig(formData)
            ElMessage.success('新增成功')
        }

        dialog.visible = false
        await loadTableData()
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
    }
}

// 重置表单
const resetForm = () => {
    Object.assign(formData, {
        regionalAlarmConfigId: null,
        areaName: '',
        alarmStatus: 1,
        alarmLevel: '',
        pushFrequency: 30,
        pushMethod: '',
        recipientId: null,
        rules: [
            {
                ruleId: null,
                parameterId: null,
                comparisonOperator: '>',
                thresholdValue: null,
                duration: 5
            }
        ],
        remark: ''
    })
}
</script>

<style scoped>
.rules-container{
    width: 100%;
}

.rule-item {
    margin-bottom: 16px;
    padding: 12px;
    background: white;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
}

.rule-item:last-child {
    margin-bottom: 0;
}

.method-tag {
    margin: 2px;
}

</style>